package com.xuwangcheng.stream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileAlreadyExistsException;

public class CopyDemo {
	public static void main(String[] args) throws IOException {
		copy("F:\\eee.pdf", "F:\\bbb.pdf");
	}
		
	public static boolean copy(String sourcePath, String targetPath) throws IOException {
		File sourceFile = new File(sourcePath);
		if (!sourceFile.isFile() || !sourceFile.canRead()) throw new IOException("不是一个可拷贝的文件");
		//if (!sourceFile.exists()) throw new FileNotFoundException();
		
		File targetFile = new File(targetPath);
		if (targetFile.exists()) throw new FileAlreadyExistsException(targetPath);
		
		InputStream input = null;
		OutputStream out = null;
		//开始拷贝文件
		try {
			input = new FileInputStream(sourceFile);
			out = new FileOutputStream(targetFile);
			
			byte[] data = new byte[2040];
			int temp = 0;
			
			long begin = System.currentTimeMillis();
			while ((temp = input.read(data)) != -1) {
				out.write(data, 0, temp);
			}
			long end = System.currentTimeMillis();
			System.out.println("耗时：" + (end - begin) + "ms.");
						
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;			
		} finally {
			if (input != null) {
				input.close();
			}
			if (out != null) {
				out.close();
			}
		}
		
		return true;
	}
}
